// pages/add/add.js
var utils = require('../../utils/utils.js');
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    winWidth: 0,
    winHeight: 0,
    currentTab: 0,
    contentImgWidth:0,
    contentImgHeight:0,
    img_url: [],
    title:'',
    content:'',
    imgPath:'',
    rgb: 'rgb(28,28,28)',
    pick: false,
    maskHidden: false,
    name: "",
    fontSize:15,
    array: [10, 11, 12, 13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30],
    index: 5,//默认显示位置
    switch_font:[],
    switch_image:[],
    value:'',
    myHeadImage:'',
    myName:'',
    imgHead:'https://www.304cloud.top:4321'
  },
  
  //字体选择
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '创作'
    })
    var that = this;
    let userID = wx.getStorageSync('openid')
    this.setData({
      userID:userID
    })
    /**
     * 获取当前设备的宽高
     */
    wx.getSystemInfo( {
        success: function( res ) {
            that.setData( {
                winWidth: res.windowWidth,
                winHeight: res.windowHeight,
                clientHeight: res.windowHeight 
            });
        }
    });
    this.getDraft();
    wx.request({
      url: 'https://www.304cloud.top:4321/cardsource',
      header:{
        'content-type':'application/json',
      },
      method:'get',
      success:res => {
        console.log(res.data.data)
        var data = res.data.data;
        this.setData({
          switch_font:data[0],
          switch_image:data[1],
          value:data[0][1].replace(' ','\n'),
          imgPath:this.data.imgHead + data[1][5]
        })
        wx.getImageInfo({
          src: this.data.imgPath,    //请求的网络图片路径
          success: (res)=>{
            //请求成功后将会生成一个本地路径即res.path,然后将该路径缓存到storageKeyUrl关键字中
            console.log(res)
            this.setData({
              netImg:res.path
            })
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成   
   */
  onReady: function () {

  },
  getDraft:function(){
    wx.request({
      url : "https://www.304cloud.top:4321/ifcreate",
      method: "GET",
      data: {
        user_id:this.data.userID
      },
      header: {
        "Content-Type": "application/json"
      },
      success: (res)=>{
        console.log(res.data.data);
        this.setData({
          draft_txt:res.data.data.draft_txt,
          draft_title:res.data.data.draft_title
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }
    wx.getUserInfo({
      lang: 'zh_CN',
      success:res => {
        console.log(res.userInfo);
        let uinfo = res.userInfo;
        this.setData({
          myHeadImage:uinfo.avatarUrl,
          myName:uinfo.nickName
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
   //  tab切换逻辑
  swichNav: function( e ) {
    var that = this;
    if( this.data.currentTab === e.target.dataset.current ) {
        return false;
    } else {
        that.setData( {
            currentTab: e.target.dataset.current
        })
    }
  },
  bindChange: function( e ) {
    var that = this;
    that.setData( { currentTab: e.detail.current });
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.img_url,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '删除图片',
      content: '确定要删除这张图片吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.img_url.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            img_url: this.data.img_url,
              hideAdd: 0
          })
        }
      }
    })
  },
  cardText:function(e){
    this.setData({
      value:e.detail.value
     })
  },
  selectImage:function(){
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9 
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有 
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有 
      success: (res)=> {
        // let  filePath = res.tempFilePaths;
        // for(var i =0;i<filePath.length;i++){
        //   wx.uploadFile({
        //     filePath: res.tempFilePaths[0],
        //     name: 'media',            
        //     url:'https://www.304cloud.top:6002/createpoem',
        //     success:res=>{
        //       console.log(res);
        //     }
        //   });
        // }
        if (res.tempFilePaths.length != 0){
          //图如果满了9张，不显示加图
          if (res.tempFilePaths.length === 1){
            that.setData({
              hideAdd:1
            })
          }else{
            that.setData({
              hideAdd: 0
            })
          }
          //把每次选择的图push进数组
          let img_url = that.data.img_url;
          for (let i = 0; i < res.tempFilePaths.length; i++) {
            img_url.push(res.tempFilePaths[i])
          }
          that.setData({
            img_url: img_url
          })
          console.log(img_url)
        }
      }
    })
  },
  input:function(e){
    this.setData({
     content:e.detail.value
    })
  },
  imgLoadFunc: function(e) {
    var tempWidth = e.detail.width; // 获取图片实际宽度
    var tempHeight = e.detail.height; // 获取图片实际高度
    this.setData({
      contentImgWidth: tempWidth,
      contentImgHeight: tempHeight
    })
  },
  // 改变字体颜色
  changeColor: function () {
    let ifpick = true;
    this.setData({
      pick: ifpick
    })
    console.log(this.data.pick)
  },
  pickColor(e) {
    this.setData({
      rgb: e.detail.color
    })
  },

  // 切换文字
   switchFont:function(){
        let switch_font = this.data.switch_font;
        let num = Math.floor(Math.random()*(switch_font.length)+1);
        console.log(num);
        switch_font = switch_font[num].replace(/\s/g,'\n')
        console.log(switch_font);
        this.setData({
          value:switch_font
        })
      },
  //网络背景
  internetBackg:function(){
        let switch_image = this.data.switch_image;
        let num = Math.floor(Math.random()*(switch_image.length)+1);
        this.setData({
          imgPath:this.data.imgHead + switch_image[num],
          imagePath:this.data.imgHead + switch_image[num]
        })
    wx.getImageInfo({
      src: this.data.imgPath,    //请求的网络图片路径
      success: (res)=>{
        //请求成功后将会生成一个本地路径即res.path,然后将该路径缓存到storageKeyUrl关键字中
        console.log(res)
        this.setData({
          netImg:res.path
        })
      }
    })
  },
  // 本地图片
  nativeBackg:function(){
    wx.chooseImage({
      count:1,
      sizeType:['original'],
      success:res=>{
        this.setData({
          imgPath:res.tempFilePaths[0],
          netImg:res.tempFilePaths[0]
        });
      }
    })
  },
  // 生成卡片
  makeTap:function(){
    var that = this;
    this.setData({
      maskHidden: false
    });
    wx.getSystemInfo({
      success(res) {
          that.setData({
              _width: res.windowWidth,
              _heigth: res.windowHeight,
              canvasType: true,
          })
      }
  })
    wx.showToast({
      title: '卡片生成中...',
      icon: 'loading',
      duration: 1000
    });
    setTimeout(function () {
      wx.hideToast()
      that.createNewImg();
      that.setData({
        maskHidden: true
      });
    }, 1000)
  },
  createNewImg: function () {
    var that = this;
    var context = wx.createCanvasContext('mycanvas');
    var coverWidth = this.data.contentImgWidth; // 封面图的宽度 裁剪需要
    var coverHeight = this.data.contentImgHeight; // 封面图的高度度 裁剪需要
    var value = this.data.value.replace(/\\n/g,'\n')
    var text = value.split('\n');
    console.log(text);
    context.setFillStyle("#ffffff")
    context.setFontSize(that.data.array[that.data.index]);
    context.fillRect(10, 10, 360, 600)
    var path = that.data.netImg;
    console.log(path);
    context.drawImage(path, 0, (coverHeight - 360 * coverWidth / 360) / 2, coverWidth, 360*coverWidth/360,10, 10, 360, 400  );
    context.setFillStyle(this.data.rgb);
    // context.setTextAlign('center');
    // context.fillText(this.data.value,150,500+i*30);
    // i=i+1;
    for(var i=0;i<text.length;i++){
      context.setTextAlign('left');
      context.fillText(text[i],50,500+i*30);
    }
    context.fillText('——'+this.data.myName,280,580);
    context.draw();
    context.arc(36, 268, 20, 0, 2 * Math.PI);
    context.clip()
    context.drawImage(this.data.myHeadImage, 16, 248 , 40, 44);
    context.setTextAlign('center');
    context.fillText(this.data.myName,150,550)
    context.restore();
    
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'mycanvas',
        success: function (res) {
          var tempFilePath = res.tempFilePath;
          that.setData({
            imagePath: tempFilePath,
            canvasHidden: true
          });
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }, 200);
  },
  //点击保存到相册
  baocun: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        wx.showModal({
          content: '卡片已保存到相册',
          showCancel: false,
          confirmText: '确定',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              /* 该隐藏的隐藏 */
              that.setData({
                maskHidden: false
              })
            }
          }, fail: function (res) {
            console.log(11111)
          }
        })
      }
    })
  },
  quxiao:function(){
    this.setData({
      maskHidden: false
    });
  },
  inputvaluetitle:function(e){
    this.setData({
      title:e.detail.value
    })
  },
  inputvaluetxt:function(e){
    this.setData({
      txt:e.detail.value
    })
  },
  // 存草稿
  save:function(){
    // var myDate = new Date();
    // var time = myDate.toLocaleString();
    // console.log(time);
    var time = utils.formatTime(new Date());
    this.setData({
      fabuTime:time
    })
    wx.request({
      url : "https://www.304cloud.top:4321/savedraft",
      method: "POST",
      data: [
        { user_id:this.data.userID},
        {
          article_title:this.data.title,
          article_txt:this.data.txt,
          article_img:"/static/image/create/poem1.png",
          article_time:time
        }
      ],
      header: {
        "Content-Type": "application/json"
      },
      
      success: function (res) {
        console.log(res.data);
        wx.showToast({
          title: '已存入草稿！',
          icon: 'success',
          duration: 2000
        })
      },
    })
    
  },
  formSubmit:function(e){
    let vals = e.detail.value;
    this.setData({
      article_title:vals.article_title,
      article_txt:vals.article_txt
    });
    console.log(this.data.article_title)
    console.log(this.data.article_txt)
      wx.uploadFile({
        filePath: this.data.img_url[0],
        name: 'media',       
        formData:{
          article_title:this.data.article_title,
          article_txt:this.data.article_txt,
          article_time:utils.formatTime(new Date()).slice(0,16),
          user_id:this.data.userID
        },    
        url:'https://www.304cloud.top:4321/createpoem',
        success:res=>{
          console.log(res);
          wx.switchTab({
            url: '/pages/star/star',
            success: function (e) {  
              var page = getCurrentPages().pop();  
              if (page == undefined || page == null) return;  
              page.onLoad();  
            } 
          })
          wx.showToast({
            title: '上传成功！',
            icon: 'success',
            duration: 3000
          })
        }
      });
  },
})